﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gx.Common.Core
{
    public static class DapperConnectionExtensions
    {
        public static PagedList<T> GetPagedList<T>(this IDbConnection dbConnection, string sql, string sort, object param = null) where T : class
        {
            string pagesql =
                    $"SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY {sort}) AS ROWNUMBER,* FROM ({sql}) AS t) TEMP_ROW WHERE ROWNUMBER BETWEEN (((@Page - 1) * @Rows) + 1) AND(@Page * @Rows);SELECT COUNT(1) AS count FROM ({sql}) AS t;";
            using (SqlMapper.GridReader gridReader = dbConnection.QueryMultiple(pagesql, param))
                return new PagedList<T>()
                {
                    List = gridReader.Read<T>().ToList(),
                    Total = gridReader.ReadFirst<int>()
                };
        }
    }
}
